//
//  TWMomentsViewController.m
//  TWHomework-WeChat
//
//  Created by wzb on 2019/11/13.
//  Copyright © 2019 WZB. All rights reserved.
//

#import "TWMomentsViewController.h"
#import "TWMomentsViewModel.h"
#import "TWTableView.h"
#import "UIImageView+TW.h"
#import "TWMomentsHeaderView.h"
#import "Define.h"
#import <Masonry.h>
#import "TWMomentsCell.h"
#import "TWTweet.h"

#define kCellId @"TWMomentsCellID"

@interface TWMomentsViewController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>
// ViewModel
@property (nonatomic, strong) TWMomentsViewModel *viewModel;
// 表格
@property (nonatomic, strong) TWTableView *tableView;
// 表头
@property (nonatomic, strong) TWMomentsHeaderView *headerView;
/// 数据源（每次展示5个）
@property (nonatomic, strong) NSMutableArray *dataSource;
/// 用来缓存cell高度
@property (nonatomic, strong) NSMutableDictionary *cellHeightCaches;

@end

@implementation TWMomentsViewController

#pragma mark - lazy
- (NSMutableDictionary *)cellHeightCaches
{
    if (!_cellHeightCaches) {
        _cellHeightCaches = [NSMutableDictionary dictionary];
    }
    return _cellHeightCaches;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - system
- (void)initUIView
{
    // 隐藏导航栏
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    // 表格
    TWTableView *tableView = [[TWTableView alloc] initWithFrame:CGRectMake(0, 0, k_screen_width, k_screen_height-k_top_height)];
    tableView.separatorInset = UIEdgeInsetsZero;
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];
    // 添加加载数据控件
    [self addPullRefresh:tableView refreshingAction:@selector(loadNewDatas)];
    [self addPullLoadMore:tableView loadMoreAction:@selector(loadMoreDatas)];
    
    self.tableView = tableView;
    
    // 表头
    TWMomentsHeaderView *headerView = [[TWMomentsHeaderView alloc] init];
    self.headerView = headerView;
    self.tableView.tableHeaderView = headerView;
    
    // 加载数据
    [self loadUserInfos];
    [self loadNewDatas];
}

- (void)layoutUI
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(k_screen_width));
        make.height.equalTo(@(kCoverImageViewH + 20));
    }];
}

- (void)initViewModelBinding
{
    self.viewModel = [[TWMomentsViewModel alloc] init];
    [self registerVM:self.viewModel];
}

#pragma mark - private
- (void)loadUserInfos
{
    // 加载个人信息
    [self.viewModel getUserInfo:^(id  _Nonnull result) {
        self.headerView.userInfo = result;
    } failure:^(NSString * _Nonnull errorString) {
        NSLog(@"error --- %@", errorString);
    }];
}
- (void)loadNewDatas
{
    /// 删除缓存
    [self.cellHeightCaches removeAllObjects];
    [self.dataSource removeAllObjects];
    
    // 加载tweets
    [self.viewModel getTweets:^(id  _Nonnull result) {
        // 重制刷新控件
        [self resetNoMoreData:self.tableView];
        [self loadMoreDatas];
    } failure:^(NSString * _Nonnull errorString) {
        NSLog(@"error --- %@", errorString);
        [self endRefresh:self.tableView];
    }];
}

- (void)loadMoreDatas
{
    // 如果已经取出全部
    if (!self.viewModel.tweets.count) {
        [self endRefresh:self.tableView];
        [self showNoMoreData:self.tableView];
        return;
    }
    /// 从viewmodel的数据中一次加入5个到dataSource
    NSMutableArray *tweets = self.viewModel.tweets.mutableCopy;
    [tweets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        /// 只取前5个
        if (idx >= 5) *stop = YES;
        [self.dataSource addObject:obj];
        [tweets removeObject:obj];
    }];
    self.viewModel.tweets = tweets;
    [self endRefresh:self.tableView];
    if (!tweets.count) {
        [self showNoMoreData:self.tableView];
    }
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TWMomentsCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    if (!cell) {
        cell = [[TWMomentsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
    }
    cell.row = indexPath.row;
    cell.tweet = [self.dataSource objectAtIndex:indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /// 先从缓存中取
    /// 如果有直接返回
    /// 如果没有就进行计算
    NSString *key = [NSString stringWithFormat:@"%zd%zd", indexPath.section, indexPath.row];
    NSNumber *cellHeight = [self.cellHeightCaches valueForKey:key];
    if (!cellHeight || [cellHeight doubleValue] <= 0) {
        TWTweet *tweet = [self.dataSource objectAtIndex:indexPath.row];
        CGFloat cellH = tweet.cellHeight;
        cellHeight = @(cellH);
        [self.cellHeightCaches setValue:cellHeight forKey:key];
    }
    return [cellHeight doubleValue];
}
@end
